package com.aviva.app.user;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

//@Transactional
@Repository
public class UserRepository
{
    @Autowired
    private LocalSessionFactoryBean sessionFactoryBean;
    
    private Session getCurrentSession(){
    	return this.sessionFactoryBean.getObject().getCurrentSession(); 
    }
    private SessionFactory getSessionFactory(){
    	return this.sessionFactoryBean.getObject().getCurrentSession().getSessionFactory(); 
    }
    
    @Transactional
    public List<User> getAllUsers()
    {
        return getCurrentSession().createCriteria(User.class).setCacheable(true).list();
    }
    @Transactional
    public void persist(User user){
    	getCurrentSession().merge(user);
    }
    
    @Transactional
    public Integer createUser(User user)
    {
    	getSessionFactory().getCache().evictEntity(user.getClass(), user.getId());
        User mergeUser =  (User)getCurrentSession().merge(user);
        return mergeUser.getId();
    }
}